package idv.kikka.server.handler;

import idv.kikka.server.common.R;
import idv.kikka.server.service.factories.SessionServiceFactory;
import idv.kikka.server.service.factories.UserServiceFactory;
import idv.kikka.server.entity.User;
import idv.kikka.common.message.LoginRequestMessage;
import idv.kikka.common.message.LoginResponseMessage;
import idv.kikka.server.service.SessionService;
import idv.kikka.server.service.UserService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

@ChannelHandler.Sharable
@Slf4j
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        UserService userService= UserServiceFactory.getUserService();
        SessionService sessionService= SessionServiceFactory.getSessionService();
//        log.info("登录操作前");
        R<User> result = userService.login(username, password);
        LoginResponseMessage responseMessage = null;
//        log.info("判断操作前");
        if(result.getCode()!=1){
//            log.info("失败操作前");
            //登录失败
            responseMessage = new LoginResponseMessage(false, result.getMsg());
        }
        else {
            //登录密码校验成功后的判断
            //获取用户的channel，判断是否在线
//            log.info("在线操作前");
            Channel channel = sessionService.getChannel(username);
            if(channel!=null){
                //如果在线就不能再登录
                responseMessage = new LoginResponseMessage(false, "该用户已经登录！");
            }else {
                //不在线就登录
                //将用户绑定到当前channel(这个channel是服务端的)
                sessionService.bind(ctx.channel(), username);
                responseMessage = new LoginResponseMessage(true, "登录成功");
            }
        }
//        log.info("写入操作前");
        //向客户端发送对应消息
        ctx.channel().writeAndFlush(responseMessage);
    }
}
